<?php

/**
 * user actions.
 *
 * @package    dnevnik
 * @subpackage user
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class userActions extends sfActions
{
 /**
  *@desc klasicna autentifikacija, provera username-a i passworda
  */
  public function executeLogin($id)
  {
      $username = urldecode($this->getRequestParameter('username'));
      $password = urldecode($this->getRequestParameter('password'));

      $profil = DbFinder::from('Profil')->where('Tip', ProfilPeer::$tip['administrator'])->where('Username', $username)->where('Password', md5($password))->findOne();
      if($profil)
      {
        $this->authenticate($profil);
      }

      $this->redirect('@homepage');
      return sfView::NONE;
  }

  /**
  *@desc logout i redirect na homepage
  */
  public function executeLogout(sfWebRequest $request)
  {
      if($this->getUser()->getAttribute('id'))
      {
         $logiranje = new Logiranje();
         $logiranje->setProfilId($this->getUser()->getAttribute('id'));
         $logiranje->setTip(LogiranjePeer::$tip['logout']);
         $logiranje->save();
      }

      $this->getUser()->setAuthenticated(false);
      $this->getUser()->clearCredentials();
      $this->getUser()->getAttributeHolder()->clear();
      header("Location: /public.php");
      die();
      $this->redirect('@homepage');
      return sfView::NONE;
  }

  private function authenticate($profil)
  {
      $profil->setLastActiv(time());
      $profil->save();
      $this->getUser()->setAuthenticated(true);
      $this->getUser()->setAttribute("id", $profil->getId());
      $this->getUser()->setAttribute("tip", $profil->getTip());

      if($profil->getTip() === ProfilPeer::$tip['administrator'])
      {
        $this->getUser()->addCredential("administrator");
      }

  }
}
